<template>
    <!-- packageA/pages/profile/profile.wxml -->

    <view class="profile" :style="'height: ' + contentHeight + 'px;'">
        <!-- 自定义导航栏 -->
        <custom-navbar :showTitle="true" :isCoverNav="true" backgroundColor="transparent" textColor="#ffffff" :showBack="false"></custom-navbar>
        <view class="profile_bg">
            <image src="https://image.shengxuankj.com/fronts/mainBg.png" mode="" />
        </view>
        <view class="profile_container" :style="'top: calc(' + navHeight + 'px + 80rpx)'">
            <view class="profile_header" @click="getLogin" v-if="!isLogin">
                <image src="https://image.shengxuankj.com/fronts/login_none.png" mode="" />
                <text class="profile_header_name">登录</text>
            </view>
            <view class="profile_header profile_header_vice" v-if="isLogin" @click="goToPage('userInfoEdit')">
                <view class="profile_header_avatar">
                    <image :src="userInfo.avatar" mode="" style="border-radius: 50%;width: 100rpx;height: 100rpx;"/>
                    <text class="profile_header_name">{{ userInfo.nickname ? userInfo.nickname : '微信用户' }}</text>
                </view>
                <view class="profile_header_arrow">
                    <image src="https://image.shengxuankj.com/fronts/arrow.png" style="width: 48rpx;height: 48rpx;"/>
                </view>
            </view>
			<view class="profile_vip" @click="toVip">
				<image class="shrink-0 image_8" src="/static/images/vip1.png" />
				<view class="profile_vip_info">
					<text class="text_7">开通加入尊享会员</text>
					<view class="profile_vip_info_join">
						<!-- <text class="font_2 text_8" v-if="content.vip&&content.vip!=0">{{content.vip_expire}}</text> -->
						<text class="font_2 text8" >加入会员</text>
						<image class="shrink-0 image_9" src="/static/images/more2.png" />
					</view>
				</view>
			</view>
            <view class="profile_orderTempalte">
                <view class="profile_orderTempalte_title">
                    <text>我的订单</text>
                    <view class="profile_orderTempalte_title_arrow">
                        <text @tap="goToOrderPage">查看全部订单</text>
                        <image src="https://image.shengxuankj.com/fronts/arrow.png" style="width: 28rpx;height: 28rpx;"/>
                    </view>
                </view>
                <view class="profile_orderTempalte_list">
                    <view class="profile_orderTempalte_list_item" :data-item="item" @tap="goToOrderPage" v-for="(item, index) in templateList" :key="index">
                        <image :src="item.url" mode="" />

                        <text>{{ item.text }}</text>
                    </view>
                </view>
            </view>
            <view class="profile_other">
				<up-cell-group>
					<!-- <up-cell title="发布故事" isLink @click="goToPage('publishStory')"></up-cell> -->
					<up-cell title="积分记录" isLink @click="goToPage('pointsRecord')"></up-cell>
					<up-cell title="联系客服" isLink @click="contactService"></up-cell>
					<up-cell title="更多" isLink @click="goToPage('more')"></up-cell>
				</up-cell-group>
            </view>
            
        </view>
        <view class="profile_logout">
            <view class="profile_logout_btn">
                <up-button round color="rgba(57, 97, 54, 1)" plain custom-class="btn" @click="handleLogout">退出登录</up-button>
            </view>
        </view>
        <!-- 悬浮球 -->
        <!-- <view class="float-ball" :style="'left: ' + floatBall.x + 'px; top: ' + floatBall.y + 'px;'">
            <image src="https://image.shengxuankj.com/fronts/service.png" mode="" />
        </view> -->
        <!-- 登录弹窗组件挂载（默认隐藏） -->
        <wx-login-popup :show="showLoginPopup" @close="onCloseLoginPopup" @success="onLoginSuccess" />
    </view>

    <!-- bindtouchstart="onFloatBallTouchStart"
          bindtouchmove="onFloatBallTouchMove"
          bindtouchend="onFloatBallTouchEnd" -->
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import customNavbar from '../../components/custom-navbar/index.vue';
import wxLoginPopup from '../../components/wx-login-popup/index.vue';
import { userInfoFun } from '@/api/port';

// 类型定义
interface UserInfo {
  name: string;
}

interface FloatBall {
  x: number;
  y: number;
  isDragging: boolean;
}

interface TemplateItem {
  id: number;
  url: string;
  text: string;
}

interface TouchEvent {
  touches: Array<{ clientX: number; clientY: number }>;
  changedTouches: Array<{ clientX: number; clientY: number }>;
}

// 响应式数据
const userInfo = ref<any>({
  name: '用户2048'
});

const showPopup = ref<boolean>(false);
const navBarHeight = ref<number>(0);
const tabBarHeight = ref<number>(0);
const contentHeight = ref<number>(0);
const navHeight = ref<number>(uni.getStorageSync('navHeight') ? uni.getStorageSync('navHeight') : 88);

// 悬浮球相关数据
const floatBall = reactive<any>({
  x: 300, // 初始x坐标
  y: 500, // 初始y坐标
  isDragging: false
});

const screenWidth = ref<number>(0);
const screenHeight = ref<number>(0);

const templateList = ref<any[]>([
  {
    id: 1,
    url: 'https://image.shengxuankj.com/fronts/obligation_icon.png',
    text: '待付款'
  },
  {
    id: 2,
    url: 'https://image.shengxuankj.com/fronts/available_for_use_icon.png',
    text: '待使用'
  },
  {
    id: 3,
    url: 'https://image.shengxuankj.com/fronts/finished_icon.png',
    text: '已完成'
  },
  {
    id: 4,
    url: 'https://image.shengxuankj.com/fronts/refund_icon.png',
    text: '退款/取消'
  }
]);

/**
 * 获取用户信息
 */
const getUserInfo = (): void => {
  // 模拟获取用户信息
  userInfoFun().then((res) => {
    if (res.code === 1) {
      userInfo.value = res.data;
      uni.setStorageSync('userInfo', res.data);
    }
  });
  // const userInfoData = uni.getStorageSync('userInfo');
  // if (userInfoData) {
  //   userInfo.value = userInfoData;
  // }
};

/**
 * 计算主要内容区域的高度
 */
const calculateContentHeight = (): void => {
  const systemInfo = uni.getSystemInfoSync();
  const windowHeight = systemInfo.windowHeight;
  const safeAreaBottom = systemInfo.safeArea ? systemInfo.screenHeight - systemInfo.safeArea.bottom : 0;
  const tabBarHeightValue = 50 + safeAreaBottom; // 自定义tabbar高度(100rpx转px约50px) + 安全区域

  // 首页导航栏不占用空间，所以内容高度就是窗口高度减去tabbar高度
  const contentHeightValue = windowHeight;
  tabBarHeight.value = tabBarHeightValue;
  contentHeight.value = contentHeightValue;
};

/**
 * 编辑个人信息
 */
const editProfile = (): void => {
  showPopup.value = true;
};

/**
 * 关闭弹窗
 */
const onClosePopup = (): void => {
  showPopup.value = false;
};

/**
 * 保存个人信息
 */
const saveProfile = (): void => {
  uni.showToast({
    title: '保存成功',
    icon: 'success'
  });
  showPopup.value = false;
};

/**
 * 返回上一页
 */
const goBack = (): void => {
  uni.navigateBack();
};

/**
 * 联系客服功能 - 对接微信小程序客服
 */
const contactService = (): void => {
  // #ifdef MP-WEIXIN
  // 微信小程序环境下使用uni-app封装的客服功能
  uni.openCustomerServiceChat({
    extInfo: {
      url: 'https://work.weixin.qq.com/kfid/kfc123456' // 替换为实际的客服链接
    },
    corpId: 'your_corp_id', // 替换为实际的企业ID
    success: (res: any) => {
      console.log('客服会话打开成功', res);
    },
    fail: (err: any) => {
      console.error('客服会话打开失败', err);
      // 降级方案：显示客服联系方式
      uni.showModal({
        title: '联系客服',
        content: '客服微信：service123\n客服电话：400-123-4567',
        showCancel: false
      });
    }
  });
  // #endif
  
  // #ifndef MP-WEIXIN
  // 非微信小程序环境的降级方案
  uni.showModal({
    title: '联系客服',
    content: '客服微信：service123\n客服电话：400-123-4567\n工作时间：9:00-18:00',
    showCancel: true,
    cancelText: '取消',
    confirmText: '复制微信号',
    success: (res) => {
      if (res.confirm) {
        // 复制客服微信号到剪贴板
        uni.setClipboardData({
          data: 'service123',
          success: () => {
            uni.showToast({
              title: '微信号已复制',
              icon: 'success'
            });
          }
        });
      }
    }
  });
  // #endif
};

// 悬浮球触摸开始
const onFloatBallTouchStart = (e: any): void => {
  floatBall.isDragging = true;
};

// 悬浮球拖拽移动
const onFloatBallTouchMove = (e: TouchEvent): void => {
  if (!floatBall.isDragging) {
    return;
  }
  const touch = e.touches[0];
  floatBall.x = touch.clientX - 30; // 减去悬浮球半径
  floatBall.y = touch.clientY - 30;
};

// 悬浮球触摸结束
const onFloatBallTouchEnd = (e: TouchEvent): void => {
  const touch = e.changedTouches[0];
  const centerX = screenWidth.value / 2;
  let targetX: number;
  if (touch.clientX < centerX) {
    // 拖到左半边，吸附到左边
    targetX = 10;
  } else {
    // 拖到右半边，吸附到右边
    targetX = screenWidth.value - 70; // 减去悬浮球宽度
  }

  floatBall.x = targetX;
  floatBall.y = touch.clientY - 30;
  floatBall.isDragging = false;
};

const goToOrderPage = (): void => {
  uni.navigateTo({
    url: '/subpackage/order/order'
  });
};

const goToPage = (pageName: string): void => {
  uni.navigateTo({
    url: `/subpackage/${pageName}/${pageName}`
  });
};


const toVip = () => {
	uni.navigateTo({
		url: '/subpackage/vipDetail/vipDetail'
	})
}

/**
 * 登录
 */
const isLogin = ref<boolean>(false)
const showLoginPopup = ref<boolean>(false)
const getLogin = () => {
	if (!ensureLogin()) {
        return
    }
}
// 统一登录判断
const ensureLogin = (): boolean => {
    const app = getApp()
    console.log(app,app?.globalData)
    if(!uni.getStorageSync('token')){
        isLogin.value = false
        showLoginPopup.value = true
        return false
    }else{
        isLogin.value = true
    }
    return true
}
// 关闭登录弹窗
const onCloseLoginPopup = (): void => {
    showLoginPopup.value = false
}

// 登录成功回调
const onLoginSuccess = (e: LoginEvent): void => {
    showLoginPopup.value = false
    isLogin.value = true
    getUserInfo();
}

/**
 * 退出登录处理函数
 */
const handleLogout = (): void => {
    uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
            if (res.confirm) {
                logout();
            }
        }
    });
};

/**
 * 退出登录函数
 */
const logout = (): void => {
    try {
        // 清除本地存储的用户数据
        uni.removeStorageSync('token');
        uni.removeStorageSync('userInfo');
        uni.removeStorageSync('userId');
        
        // 清除全局数据
        const app = getApp();
        if (app.globalData) {
            app.globalData.token = '';
            app.globalData.userInfo = null;
            app.globalData.userId = '';
            app.globalData.isLogin = false;
        }
        
        // 重置页面状态
        isLogin.value = false;
        userInfo.value = {
            name: '用户2048'
        };
        
        // 显示退出成功提示
        uni.showToast({
            title: '退出登录成功',
            icon: 'success',
            duration: 2000
        });
        
    } catch (error) {
        console.error('退出登录失败：', error);
        uni.showToast({
            title: '退出登录失败',
            icon: 'none',
            duration: 2000
        });
    }
};

/**
 * 生命周期函数--监听页面加载
 */
onMounted(() => {
    // 获取屏幕尺寸
    const systemInfo = uni.getSystemInfoSync();
    screenWidth.value = systemInfo.windowWidth;
    screenHeight.value = systemInfo.windowHeight;

    // 计算剩余可视高度
    calculateContentHeight();
    // 登录判断
    if(ensureLogin()){
        getUserInfo();
    }else{
        isLogin.value = true
    }

});

</script>
<style>
/* packageA/pages/profile/profile.wxss */
.profile {
    background-color: #f5f5f5;
    width: 100%;
    position: relative;
}
.profile_bg {
    width: 100%;
    height: 490rpx;
}
.profile_bg image {
    width: 100%;
    height: 100%;
}

.profile_container {
    position: absolute;
    width: 100%;
    left: 0;
    padding: 0 30rpx 50rpx 30rpx;
    box-sizing: border-box;
}
.profile_header {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 0 30rpx 0 26rpx;
    box-sizing: border-box;
    border-radius: 50%;
}
.profile_header_vice{
    justify-content: space-between;
}
.profile_header_avatar{
    display: flex;
    align-items: center;
    justify-content: flex-start;
}

.profile_header image {
    width: 80rpx;
    height: 80rpx;
}

.profile_header text {
    /** 文本1 */
    font-size: 36rpx;
    font-weight: bold;
    letter-spacing: 0px;
    color: rgba(19, 19, 19, 1);
    margin-left: 24rpx;
}

.profile_orderTempalte {
	margin-top: 24rpx;
    width: 100%;
    padding: 30rpx 25rpx 35rpx 25rpx;
    box-sizing: border-box;
    background-color: #ffffff;
    border-radius: 10rpx;
}
.profile_orderTempalte .profile_orderTempalte_title {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.profile_orderTempalte_title text:nth-child(1) {
    /** 文本1 */
    font-size: 32rpx;
    font-weight: 400;
    letter-spacing: 0px;
    color: rgba(19, 19, 19, 1);
}
.profile_orderTempalte_title text:nth-child(2) {
    /** 文本1 */
    font-size: 24rpx;
    font-weight: 400;
    letter-spacing: 0px;
    color: rgba(153, 153, 153, 1);
}

.profile_orderTempalte_list {
    width: 100%;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    margin-top: 30rpx;
}
.profile_orderTempalte_list .profile_orderTempalte_list_item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.profile_orderTempalte_list .profile_orderTempalte_list_item image {
    width: 56rpx;
    height: 56rpx;
}

.profile_orderTempalte_list .profile_orderTempalte_list_item text {
    /** 文本1 */
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 40.54rpx;
    color: rgba(85, 85, 85, 1);
    margin-top: 8rpx;
}
.profile_other {
	background-color: #ffffff;
    margin-top: 30rpx;
	border-radius: 10rpx;
}
.otherImg {
    width: 36rpx;
    height: 36rpx;
}

.cell-group {
    margin: 0 !important;
}

.profile_logout {
    width: 100%;
    padding: 0 80rpx;
    box-sizing: border-box;
    height: 80rpx;
    position: absolute;
    bottom: 50rpx;
    left: 50%;
    transform: translateX(-50%);
}
.profile_logout .profile_logout_btn {
    width: 100%;
    height: 100%;
}
.profile_logout .profile_logout_btn .btn {
    width: 100%;
    margin: 0 !important;
    height: 100%;
}

/* 悬浮球样式 */
.float-ball {
    position: fixed;
    width: 128rpx;
    height: 128rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    /* box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15); */
    z-index: 9999;
    /* transition: all 0.3s ease; */
    cursor: pointer;
}

.float-ball:active {
	background-color: transparent;
	background: transparent;
    /* transform: scale(0.95); */
}

.float-ball image {
    width: 100%;
    height: 100%;
}


.profile_vip {
	width: 100%;
	padding-left: 32rpx;
	margin-top: 64rpx;
	box-sizing: border-box;
	background-color: #ffff00;
	background-image: linear-gradient(90deg, #fee9bb 0%, #f6dcac 100%),
		linear-gradient(45deg, #f0ddb6 0%, #f6e7cf 100%),
		linear-gradient(165deg, #f6e0b8 0%, #fdcb78 50%, #f9d38c 100%),
		linear-gradient(88deg, #fff2e9 0%, #ffcfab 50%, #d19f75 100%),
		linear-gradient(165deg, #fef9ef 0%, #ffdeb9 50%, #d19f75 100%),
		linear-gradient(165deg, #fef9ef 0%, #d19f75 100%);
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: flex-start;
}
.image_8 {
	width: 58rpx;
	height: 53rpx;
}
.text_7 {
	color: #512c19;
	font-size: 28rpx;
	font-family: PingFangSC;
	line-height: 27rpx;
}
.group_3 {
	margin-right: 30rpx;
}
.text_8 {
	color: #ad6540;
	line-height: 22rpx;
}
.text8 {
	color: #512C19;
	line-height: 22rpx;
}
.image_9 {
	width: 34rpx;
	height: 34rpx;
}
.profile_vip_info {
	width: calc(100% - 58rpx);
	padding: 30rpx 30rpx 30rpx 0;
	border-radius: 0px 20rpx 20rpx 0px;
	background-image: url('https://codefun-proj-user-res-1256085488.cos.ap-guangzhou.myqcloud.com/65289a27ce83440011a2c3ab/16971889172326808404.png');
	background-size: 100% 100%;
	background-repeat: no-repeat;
	height: 95rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-left: 16rpx;
	box-sizing: border-box;
}
.profile_vip_info_join{
	display: flex;
	align-items: center;
	justify-content: flex-end;
}
</style>
